<?php

namespace Admin\Controller;

use Common\Lib\Tree;

class ArticleController extends AdminController {

    public function index() {
        $catid = I('category_id', 0, 'intval');
        if (!$catid) {
            $this->error('请选择分类进行管理');
        }
        $category = M('ArticleCategory')->where(['id' => $catid])->find();

        if (!$category) {
            $this->error('分类不存在');
        }
        if ($category['type'] == 1) {
            $this->articleList($category);
        } else {
            redirect(U('article/page_add', ['id' => $category['id']]));
        }
    }

    protected function articleList($category) {
        $keyword = I('keyword', '', 'addslashes');
        $where = ['category_id' => $category['id']];
        if ($keyword) {
            $where['title'] = ['like', "%{$keyword}%"];
        }

        $total = M('Article')->where($where)->count();
        $Page = new \Think\Page($total, 20);
        $result = M('Article')->where($where)->order('sort ASC,id DESC')->page($Page->nowPage, $Page->listRows)->select();
        $category_list = M('ArticleCategory')->where(['id' => ['neq', $category['id']], 'type' => 1])->order('sort ASC')->select();
        foreach ($category_list as $key => $cat) {
            if (!$this->hasChilds($category_list, $cat['id'])) {
                $category_list[$key]['move_url'] = U('article/move', ['category_id' => $cat['id']]);
            } else {
                $category_list[$key]['move_url'] = '';
            }
        }
        $Tree = new Tree($category_list);
        $Tree->icon = array("&nbsp;&nbsp;&nbsp;&nbsp; ", "&nbsp;&nbsp;&nbsp;├─ ", "&nbsp;&nbsp;&nbsp;└─ ");
        $Tree->nbsp = "&nbsp;&nbsp;&nbsp;";
        $html = "<li><a href='javascript:void(0);'  data-action='\$move_url' data-confirmtext='确定移动已选中的文章到<\$name>？'><span class='spacer'>\$spacer</span>\$name</a></li>";
        $category_html = $Tree->get_tree(0, $html);

        if (!$category['url']) {
            $category['path'] = '/article';
        } else {
            $category['path'] = $category['url'];
        }
        foreach ($result as $key => $val) {
            $result[$key]['url'] = U($category['path'] . '/view/' . $val['id']);
        }
        $this->assign('category', $category);
        $this->assign('category_list', $category_list);
        $this->assign('category_html', $category_html);
        $this->assign('result', $result);
        $this->assign('page', $Page->show());
        $this->display('list');
    }

    protected function hasChilds($category, $pid) {
        foreach ($category as $val) {
            if ($val['pid'] == $pid) {
                return true;
            }
        }
        return false;
    }

    public function add() {
        if (IS_POST) {
            $data = [
                'title' => I('title'),
                'category_id' => I('category_id'),
                'summary' => I('summary'),
                'content' => I('content'),
                'author' => I('source', '', 'author'),
                'source' => I('source', '', 'addslashes'),
                'seo_title' => I('seo_title'),
                'seo_keywords' => I('seo_keywords'),
                'seo_description' => I('seo_description'),
                'created_at' => time(),
            ];
            if (strlen($data['title']) < 5) {
                $this->error('标题长度过短');
            }
            if (!$data['category_id']) {
                $this->error('分类不能为空');
            }
            if ($data['summary']) {
                $data['summary'] = msubstr($data['summary'], 200);
            } else {
                $data['summary'] = msubstr(strip_tags(htmlspecialchars_decode($data['content'])), 200);
            }
            if ($_FILES['thumb']) {
                $thumb = $this->uploadImage($_FILES['thumb']);
                $data['thumb'] = $thumb;
            } else {
                $data['thumb'] = I('default_photo');
            }
            if (M('Article')->data($data)->add()) {
                $this->success('添加成功', U('Article/index', ['category_id' => $data['category_id']]));
            } else {
                $this->error('添加失败');
            }
        } else {
            $this->assign('category_list', $this->treeCategory(I('categroy_id', 0, 'intval'), [], 1));
            $this->display();
        }
    }

    public function edit() {
        $id = I('id', 0, 'intval');
        $result = M('Article')->find($id);
        if (!$result) {
            $this->error('文章不存在');
        }
        if (IS_POST) {
            $data = [
                'id' => I('id', '0', 'intval'),
                'title' => I('title'),
                'category_id' => I('category_id'),
                'summary' => I('summary'),
                'player' => I('player'),
                'content' => I('content'),
                'top' => I('top', 0, 'intval'),
                'author' => I('source', '', 'author'),
                'source' => I('source', '', 'addslashes'),
                'seo_title' => I('seo_title'),
                'seo_keywords' => I('seo_keywords'),
                'seo_description' => I('seo_description'),
            ];
            if (strlen($data['title']) < 5) {
                $this->error('标题长度过短');
            }
            if (!$data['category_id']) {
                $this->error('分类不能为空');
            }

            if ($data['summary']) {
                $data['summary'] = msubstr($data['summary'], 200);
            } else {
                $data['summary'] = msubstr(strip_tags(htmlspecialchars_decode($data['content'])), 200);
            }
            if ($_FILES['thumb']) {
                $thumb = $this->uploadImage($_FILES['thumb']);
                $data['thumb'] = $thumb;
            } else {
                $default_photo = I('default_photo');
                if (!empty($default_photo)) {
                    $data['thumb'] = $default_photo;
                }
            }
            if (M('Article')->data($data)->save() !== false) {
                $this->success('编辑成功', U('Article/index', ['category_id' => $data['category_id']]));
            } else {
                $this->error('编辑失败');
            }
        } else {
            $result['content'] = htmlspecialchars_decode($result['content']);
            $this->assign('category_list', $this->treeCategory($result['category_id'], [], 1));
            $this->assign($result);
            $this->display();
        }
    }

    public function sort() {
        $sort = I('sort', 0, 'intval');
        $ids = I('id', 0, 'intval');
        foreach ($ids as $id) {
            M('Article')->where(['id' => $id])->setField('sort', $sort[$id]);
        }
        $this->success();
    }

    public function delete() {
        $id = I('id', 0, 'intval');
        if (!is_array($id)) {
            $id = [$id];
        }
        M('Article')->where(['id' => ['in', $id]])->delete();
        $this->success('删除成功');
    }

    public function move() {
        $id = I('id', 0, 'intval');
        if (!is_array($id)) {
            $id = [$id];
        }
        $catid = I('get.category_id', 0, 'intval');
        $category = M('ArticleCategory')->where(['type' => 1, 'id' => $catid])->find();
        if (!$category) {
            $this->error('分类不存在');
        }
        $childs = M('ArticleCategory')->where(['pid' => $catid])->count();
        if ($childs) {
            $this->error('无法移动到当前分类');
        }
        M('Article')->where(['id' => ['in', $id]])->setField('category_id', $catid);
        $this->success('文章移动成功');
    }

    public function page_add() {
        if (IS_POST) {
            $data = [
                'id' => I('id', 0, 'intval'),
                'title' => I('title'),
                'url' => I('url'),
                'content' => I('content')
            ];
            $result = M('ArticlePage')->find($data['id']);
            if (!$result) {
                $data['created_at'] = time();
                $return = M('ArticlePage')->data($data)->add();
            } else {
                $return = M('ArticlePage')->data($data)->save();
            }
            if ($return !== false) {
                $this->success('编辑成功', U('article/page_add', ['category_id' => $data['id']]));
            } else {
                $this->error('编辑失败', U('article/page_add', ['category_id' => $data['id']]));
            }
        } else {
            $id = I('id', 0, 'intval');
            $category = M('ArticleCategory')->find($id);
            if (!$category) {
                $this->error('分类不存在');
            }
            if ($category['type'] != 2) {
                redirect(U('article/add'));
            }

            $result = M('ArticlePage')->find($id);

            if (!$result) {
                $result['id'] = $id;
                $result['title'] = $category['name'];
            } else {
                $result['content'] = htmlspecialchars_decode($result['content']);
            }
            $this->assign($result);
            $this->assign('category', $category);
            $this->assign('category_list', $this->treeCategory(I('category_id', 0, 'intval')));
            $this->display('page_add');
        }
    }

    public function category() {
        $result = M('ArticleCategory')->order('pid ASC,sort ASC,id ASC')->select();
        foreach ($result as $key => $val) {
            $result[$key]['add'] = '<a href="' . U('article/category_add', ['pid' => $val['id']]) . '" class=" tooltip-info ajax-load" data-toggle="tooltip" data-placement="right" data-original-title="添加子分类"><i class="fa fa-plus"></i></a>';
            $result[$key]['delete_link'] = U('article/category_delete', ['id' => $val['id']]);
            $result[$key]['edit_link'] = U('article/category_edit', ['id' => $val['id']]);
            $result[$key]['type'] = $val['type'] == 1 ? '列表' : '单页';
        }
        $Tree = new Tree($result);
        $Tree->icon = array("&nbsp;&nbsp;&nbsp;&nbsp; ", "&nbsp;&nbsp;&nbsp;├─ ", "&nbsp;&nbsp;&nbsp;└─ ");
        $Tree->nbsp = "&nbsp;&nbsp;&nbsp;";
        $html = "<tr>                    
                    <td width='80' class='input-group-xs'><input type='text' name='sort[\$id]' style='text-align:center' value='\$sort' class='form-control' /></td>
                    <td width='80' class='text-align-center'>\$id</td>
                    <td class='left'><span class='spacer'>\$spacer</span> \$name \$add</td>
                    <td class='text-align-center'>\$type</td>
                    <td class='text-align-center'><a href='\$edit_link' class='ajax-load' ><i class='fa fa-edit'></i> 编辑</a> <a href='\$delete_link'  class='margin-left-10 ajax-link' data-confirm='确定删除该分类？'><i class='fa fa-trash-o'></i> 删除</a></td>
            </tr>";

        $result = $Tree->get_tree(0, $html);
        $this->assign('result', $result);
        $this->display();
    }

    public function category_add() {
        if (IS_POST) {
            $data = I('post.');
            if (!$data['name']) {
                $this->error('分类名不能为空');
            }

            if (M('ArticleCategory')->data($data)->add()) {
                $this->success('分类添加成功');
            } else {
                $this->error('分类添加失败');
            }
        } else {
            $pid = I('pid', 0, 'intval');
            $result = M('ArticleCategory')->where(['id' => $pid])->field('type')->find();
            $this->assign($result);
            $this->assign($this->templateList());
            $this->assign('category_list', $this->treeCategory($pid));
            $this->display();
        }
    }

    public function category_edit() {
        if (IS_POST) {
            $data = I('post.');
            if (!$data['name']) {
                $this->error('分类名不能为空');
            }
            if (M('ArticleCategory')->data($data)->save() !== false) {
                $this->success('分类修改成功');
            } else {
                $this->error('分类修改失败');
            }
        } else {
            $id = I('id', 0, 'intval');
            $result = M('ArticleCategory')->find($id);
            $this->assign($result);
            $this->assign($this->templateList());
            $this->assign('category_list', $this->treeCategory($result['pid'], $id));
            $this->display();
        }
    }

    public function category_delete() {
        $id = I('id', 0, 'intval');
        $total = M('ArticleCategory')->where(['pid' => $id])->count();
        if ($total) {
            $this->error('该分类下包含子分类，无法删除');
        }
        M('ArticleCategory')->delete($id);
        $this->success('分类删除成功');
    }

    public function treeCategory($selected = 0, $exclude = array(), $has_type = 0) {
        $where = [];
        if (!empty($exclude)) {
            $where = ['id' => ['neq', $exclude]];
        }
        if (in_array($has_type, [1, 2])) {
            $where['type'] = $has_type;
        }
        $result = M('ArticleCategory')->where($where)->order('pid ASC,sort ASC')->select();
        $Tree = new Tree($result);
        $html = "<option data-type='\$type' value='\$id' \$selected>\$spacer \$name</option>";
        $result = $Tree->get_tree(0, $html, $selected, '&nbsp;&nbsp;&nbsp;&nbsp;');
        return $result;
    }

    /**
     * 分类排序
     */
    public function category_sort() {
        $sorts = I('sort', 0, 'intval');
        foreach ($sorts as $key => $val) {
            M('ArticleCategory')->where(['id' => $key])->setField('sort', $val);
        }
        $this->success('操作成功');
    }

    public function templateList() {
        $types = ['index', 'page', 'list', 'view'];
        $templates = [];
        foreach ($types as $type) {
            $files = glob(APP_PATH . '/Home/View/Article/' . $type . '_*.html');
            array_walk($files, function (&$a) {
                $a = basename($a);
            });
            $templates['template_' . $type . '_list'] = $files;
        }

        return $templates;
    }

    public function category_cache() {
        $urls = M('ArticleCategory')->getField('id,url');
        S('ArticleUrl', $urls);

        $result = M('ArticleCategory')->select();
        $category = [];
        foreach ($result as $val) {
            $category[$val['id']] = $val;
        }
        S('ArticleCategory', $category);
        $this->success('缓存更新成功');
    }

}
